﻿Imports System.Net.Sockets
Imports System.Net
Imports System.Text
Imports System.Threading


Module Comunicacao

    Dim clientSocket As New TcpClient()
    Dim serverStream As NetworkStream
    Dim lerDados As String

    Public Sub Inicializa()

        lerDados = "Conectado com o Servidor ..."
        Mensagem()

        Try
            clientSocket.Connect("127.0.0.1", 8888)
            serverStream = clientSocket.GetStream()

            Dim outStream As Byte() = Encoding.ASCII.GetBytes(txtNome.Text + "$")
            serverStream.Write(outStream, 0, outStream.Length)
            serverStream.Flush()

            Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf getMensagem)
            ctThread.Start()

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

    Private Sub Mensagem()
        If InvokeRequired Then
            Invoke(New MethodInvoker(AddressOf Mensagem))
        Else
            txtDados.Text = txtDados.Text + Environment.NewLine + " >> " + lerDados
        End If
    End Sub

    Sub msg(ByVal mesg As String)
        mesg.Trim()
        'Console.WriteLine(" >> " + mesg)
        Cliente.EstadoConexao = mesg
    End Sub

    Public Class trataCliente
        Dim clientSocket As TcpClient
        Dim clNo As String
        Public Sub iniciarCliente(ByVal inClientSocket As TcpClient, ByVal clineNo As String)
            Me.clientSocket = inClientSocket
            Me.clNo = clineNo
            Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat)
            ctThread.Start()
        End Sub

        Private Sub doChat()

            Dim requestCount As Integer
            Dim bytesFrom(10024) As Byte
            Dim dataFromClient As String
            Dim sendBytes As [Byte]()
            Dim serverResponse As String
            Dim rCount As String

            requestCount = 0

            'While (True)
            Try
                requestCount = requestCount + 1
                Dim networkStream As NetworkStream = clientSocket.GetStream()
                networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))

                dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
                dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"))

                msg("Do cliente-" + clNo + dataFromClient)

                rCount = Convert.ToString(requestCount)
                serverResponse = "Servidor para o cliente(" + clNo + ") " + rCount
                sendBytes = Encoding.ASCII.GetBytes(serverResponse)

                networkStream.Write(sendBytes, 0, sendBytes.Length)
                networkStream.Flush()
                msg(serverResponse)

            Catch ex As Exception
                MsgBox(ex.ToString)
            End Try

            'End While

        End Sub
    End Class

End Module
